import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { InjectRepository } from '@nestjs/typeorm';
import { Model } from 'mongoose';
import { type } from 'os';
import { ChargeOrder } from 'src/entities/ChargeOrder';
import { ChargeOrderRealTimeInfo, ChargeOrderRealTimeInfoDocument } from 'src/schemas/ChargeOrderRealTimeInfo.schema';
import { ChargeOrderRecord } from 'src/types';
import { FindConditions, In, LessThan, Like, Repository } from 'typeorm';

@Injectable()
export class ChargeOrderService {
    constructor(
        @InjectRepository(ChargeOrder) protected repository:Repository<ChargeOrder>,
        @InjectModel(ChargeOrderRealTimeInfo.name) private chargeOrderRealTimeInfoModel: Model<ChargeOrderRealTimeInfoDocument>
    ){}

    async page(query:Pagination, userId:number) {
        let where:FindConditions<ChargeOrder> = { userId }
        const lastId = query.lastKey || 0
        const pageSize = query.pageSize || 20

        if(lastId > 0) {
            where.orderId = LessThan(lastId)
        }

        let rows:ChargeOrderRecord[] = await this.repository.find({
            where,
            select : ['orderId', 'orderNo', 'deviceId', 'createTime', 'endTime', 'status', 'consumeAmount'], 
            skip : 0, 
            take : pageSize, 
            order : {orderId : 'DESC'}
        })

        return rows
    }

    async order(orderId:number, fields?:(keyof ChargeOrder)[]) {
        let order:ChargeOrderRecord = await this.repository.findOne(orderId, {
            select : fields
        })

        return order
    }

    async chargingOrder(orderIds:number[]) :Promise<ChargeOrderRecord[]>{
        
        return await this.repository.find({
            where : {
                orderId : In(orderIds)
            },
            select : ['orderId', 'orderNo', 'status', 'deviceId', 'portNo', 'chargeAmount', 'strategyType', 'createTime']
        })
    }

    async realTimeInfo(orderIds:number[]|number) {
        const field = {_id : 1, lastData: {consumeTime : 1, power : 1, voltage : 1, consumeEnergy : 1}}
        if(Array.isArray(orderIds)) {
            return this.chargeOrderRealTimeInfoModel.find({$or : orderIds.map(id => ({_id : id}))}, field)
        }else {
            return this.chargeOrderRealTimeInfoModel.findById(orderIds, field)
        }
        
    }

    async power(orderId:number) {
        const res = await this.chargeOrderRealTimeInfoModel.findById(orderId, {data : {updateTime : 1, power:1}})
        return res && res.data ? res.data : null
    }
}
